//
//  NSDate+Category.m
//  PiPiPineapple
//
//  Created by 李晓东 on 17/11/4.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

#import "NSDate+Category.h"

@implementation NSDate (Category)
- (BOOL)compareDateWhoIsOlder:(NSDate *)otherDate{
    
    
    NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    NSCalendarUnit calendarUnit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitDay;
    NSDateComponents *components = [calendar components:calendarUnit fromDate:self];
    NSDateComponents *otherComponents = [calendar components:calendarUnit fromDate:otherDate];
    if (components.year != otherComponents.year) {
        // 不在同一年直接返回 YES
        return YES;
    }
    
    BOOL flag = NO;
    // 先判断当天是否是开奖日,如果是开奖日,直接返回 yes.
    // 如果不是,则判断是数据库中最新一期的时间和今天相比,中间是否有新的开奖记录
    switch (components.weekday) {
        case 1:
        // sunday
        case 3:
        // tuseday
        case 5:
        //thursday
            flag = YES;
            break;
        case 2:
        // monday
        case 4:
        // wednesday
        case 6:
        // firday
        case 7:
        // saturday
            flag = NO;
            break;
    }
    
    NSTimeInterval timeInterval = [self timeIntervalSinceDate:otherDate];
    if(!flag){
        // 数据库最新一条记录和当前时间间隔超过24(或者最后一条记录是否周四?周四下期开奖时间在周日,所以间隔2天,是48)小时,则有可能有新开奖记录产生
        if (timeInterval >= (60 * 60 * 24 * (otherComponents.weekday == 5 ? 3 : 2) )) {
            return YES;
        }
        return NO;
    }
    // 今天是开奖日,但数据库中已经有了改天的记录了.不再网络加载
    if(flag){
        if (components.day != otherComponents.day && timeInterval >= (60 * 60 * 24 * (otherComponents.weekday == 5 ? 3 : 2 ))) {
            return YES;
        }
        return NO;
    }
    
    return YES;
}

- (NSTimeInterval)timeIntervalBetween:(NSData *)otherData{
    NSTimeInterval timeInterval = [self timeIntervalSinceDate:otherData];
    int day = timeInterval / 60 / 60 / 24;
    return 0;
}

@end
